package com.example.testsbjenkins.CompletableFuture;

import cn.hutool.core.date.StopWatch;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author: lt
 * @date: 2022/6/24 16:34
 * @Description: todo
 */
public class CompletableFutureTest {

    public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {

        UserInfoService userInfoService = new UserInfoService();
        MedalService medalService = new MedalService();
        long userId =666L;
        StopWatch stopWatch = StopWatch.create("task");

        stopWatch.start();
        //调用用户服务获取用户基本信息
        CompletableFuture<UserInfo> userInfoCompletableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                return userInfoService.getUserInfo(userId);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        }).whenComplete((u,throwable)->{

            System.out.println(u);
        });
        Thread.sleep(300); //模拟主线程其它操作耗时
        //医疗信息
        CompletableFuture<MedalInfo> medalInfoCompletableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                return medalService.getMedalInfo(userId);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        });
        UserInfo userInfo = userInfoCompletableFuture.get(2, TimeUnit.SECONDS);
        MedalInfo medalInfo = medalInfoCompletableFuture.get();
        stopWatch.stop();
        System.out.println("总共用时" + stopWatch.getTotalTimeMillis() + "ms");

    }
}
